package com.yeyouluo.zk;

import org.I0Itec.zkclient.ZkClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Client {
    List<String> severList = new ArrayList<>();
    public ZkClient zkClient = new ZkClient(MyTimeServer.ZK_ADDR);

    public static void main(String[] args) throws InterruptedException {
        Client client = new Client();
        client.init();
        while (true) {
            try {
                client.sendRequest(); //发送请求
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    client.sendRequest();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            //每隔几秒中发送一次请求到服务端
            Thread.sleep(2000);
        }
    }

    public void init() {
        //第一次获取服务器信息,所有的子节点
        List<String> server = zkClient.getChildren(MyTimeServer.SERVERS_PATH);
        server.forEach(x -> {
            Object data = zkClient.readData(MyTimeServer.SERVERS_PATH + "/" + x);
            severList.add(String.valueOf(data));
        });

        //对servers目录进行监听
        zkClient.subscribeChildChanges(MyTimeServer.SERVERS_PATH, (s, children) -> {
            //接收到通知，说明节点发生了变化，client需要更新infos集合中的数据
            ArrayList<String> list = new ArrayList<>();
            //遍历更新过后的所有节点信息
            for (String path : children) {
                final Object o = zkClient.readData(MyTimeServer.SERVERS_PATH + "/" + path);
                list.add(String.valueOf(o));
            }

            //最新数据覆盖老数据
            severList = list;
            System.out.println("--》接收到通知，最新服务器信息为：" + severList);
        });
    }

    //发送时间查询的请求
    public void sendRequest() throws IOException {
        //目标服务器地址
        final Random random = new Random();
        final int i = random.nextInt(severList.size());
        final String ipPort = severList.get(i);
        final String[] arr = ipPort.split(":");

        //建立socket连接

        final Socket socket = new Socket(arr[0], Integer.parseInt(arr[1]));
        final OutputStream out = socket.getOutputStream();
        final InputStream in = socket.getInputStream();
        //发送数据
        out.write("query time".getBytes());
        out.flush();
        //接收返回结果
        final byte[] b = new byte[1024];
        in.read(b);//读取服务端返回数据
        System.out.println("client端接收到server:+" + ipPort + "+返回结果：" + new String(b));


        //释放资源
        in.close();
        out.close();
        socket.close();
    }

}
